<template>
  <div class="login">
    <el-form
      v-if="showBol"
      ref="loginFormRef"
      :model="loginForm"
      :rules="loginRules"
      size="large"
    >
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          placeholder="用户名：字母开头，长度不小于三位"
        >
          <template #prefix>
            <el-icon class="el-input__icon"></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          type="password"
          v-model="loginForm.password"
          placeholder="密码：字母开度，长度不小于6位"
          show-password
          autocomplete="new-password"
        >
          <template #prefix>
            <el-icon class="el-input__icon"></el-icon>
          </template>
        </el-input>
      </el-form-item>
    </el-form>

    <el-form
      v-if="!showBol"
      ref="loginFormRef1"
      :model="loginForm"
      :rules="loginRules"
      size="large"
    >
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          placeholder="用户名：长度不小于三位"
        >
          <template #prefix>
            <el-icon class="el-input__icon"></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          type="password"
          v-model="loginForm.password"
          placeholder="密码：长度不小于6位"
          show-password
          autocomplete="new-password"
        >
          <template #prefix>
            <el-icon class="el-input__icon"></el-icon>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <div class="login-btn">
      <el-button
        :icon="CircleClose"
        round
        @click="resetForm(loginFormRef1)"
        size="large"
        >重置
      </el-button>

      <el-button
        v-if="showBol"
        :icon="UserFilled"
        round
        @click="login(loginFormRef)"
        size="large"
        type="primary"
        :loading="loading"
      >
        登陆
      </el-button>

      <el-button
        v-if="!showBol"
        :icon="UserFilled"
        round
        @click="register(loginFormRef1)"
        size="large"
        type="primary"
        :loading="loading"
      >
        注册
      </el-button>
    </div>
    <div v-if="showBol" class="register">
      没有账号？<span @click="change">点击注册</span>
    </div>
    <div v-if="!showBol" class="register">
      已有账号？<span @click="change">点击登陆</span>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElNotification } from "element-plus";
import { globals } from "@/store/index.js";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import { ElForm } from "element-plus";
import { userInfo } from "@/store/user.js";
import { userNameRegExp, userPassRegExp } from "@/hooks/loginReg.js";
import { userLogin, useRegister } from "@/require/index.js";
const router = useRouter();
const store = userInfo();
const globalStore = globals();
const loginFormRef = ref();
const loginFormRef1 = ref();
let showBol = ref(true);
const loginRules = reactive({
  username: [
    { required: userNameRegExp, message: "请输入用户名", trigger: "blur" },
  ],
  password: [
    { required: userPassRegExp, message: "请输入密码", trigger: "blur" },
  ],
});
const loading = ref(false);
const loginForm = ref({ username: "", password: "" });
const login = (formEl) => {
  if (!formEl) return;
  console.log(1111);
  formEl.validate(async (valid) => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      let { data } = await userLogin({ ...loginForm.value });
      console.log(data);
      if (data.code == "200") {
        store.info = data.data;
        localStorage.setItem("token", data.data.token);
        router.push({ path: "/home/index" });
        ElNotification({
          title: store.info.username,
          message: "欢迎登录！",
          type: "success",
          duration: 1500,
        });
      } else {
        ElNotification({
          title: store.info.username,
          message: "账号或密码错误！",
          type: "error",
          duration: 1500,
        });
      }
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};

const register = async (formEl) => {
  let { data } = await useRegister({ ...loginForm.value });
  //  console.log(data);
  if (data.code == "200") {
    loginForm.value = {
      username: "",
      password: "",
    };
  }
};

const change = () => {
  loginForm.value = {
    username: "",
    password: "",
  };
  showBol.value = !showBol.value;
};
onMounted(() => {
  // 监听enter事件（调用登录）
  document.onkeydown = (e) => {
    e = window.event || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="less">
@import "./login.css";

.register {
  position: absolute;
  bottom: 5px;
  right: 5px;
  font-size: 14px;

  span {
    font-size: 12px;

    &:hover {
      cursor: pointer;
    }
  }
}
</style>
